<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\Redis;
use GuzzleHttp\Exception\GuzzleException;

class SwooleSendMsg extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'swoole:send:msg';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '推送websocket消息';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $key = config('freeswitch.redis_key.send_msg');
        while (true) {
            $item = Redis::lpop($key);
            if($item == null){
                sleep(4);
                continue;
            }
            $item = json_decode($item, true);
            try {
                $users = \App\Models\User::query()->pluck('nickname', 'id')->toArray();
                foreach ($item['accept_user_ids'] as $accept_user_id) {
                    \App\Models\Message::create([
                        'send_user_id' => $item['send_user_id'],
                        'send_user_nickname' => \Illuminate\Support\Arr::get($users, $item['send_user_id'], null),
                        'accept_user_id' => $accept_user_id,
                        'accept_user_nickname' => \Illuminate\Support\Arr::get($users, $accept_user_id, null),
                        'title' => $item['data']['title'] ?? null,
                        'content' => $item['data']['content'] ?? null,
                    ]);
                }
                $client = new \GuzzleHttp\Client();
                $client->post('http://127.0.0.1:9502', [
                    'json' => [
                        'scene' => $item['scene'],
                        'data' => $item['data']['title']??null,
                        'user_ids' => $item['accept_user_ids'],
                    ],
                    'timeout' => 5,
                ]);
                return true;
            } catch (GuzzleException $exception) {
                \Illuminate\Support\Facades\Log::error('推送消息异常：' . $exception->getMessage());
                return false;
            }

        }
    }
}
